package com.mmc.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mmc.entity.Message;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息数据访问层
 *
 * @author kunfe
 * @since 2024-01-01
 */
@Mapper
public interface MessageMapper extends BaseMapper<Message> {

    /**
     * 根据接收者ID查询未读消息数量
     */
    default Long countUnreadByReceiverId(Long receiverId) {
        return selectCount(new LambdaQueryWrapper<Message>()
                .eq(Message::getReceiverId, receiverId)
                .eq(Message::getStatus, 0)
                .eq(Message::getDeleted, 0));
    }

    /**
     * 根据接收者ID分页查询消息
     */
    default Page<Message> selectPageByReceiverId(Page<Message> page, Long receiverId, Integer type, Integer status) {
        LambdaQueryWrapper<Message> wrapper = new LambdaQueryWrapper<Message>()
                .eq(Message::getReceiverId, receiverId)
                .eq(Message::getDeleted, 0)
                .orderByDesc(Message::getIsTop)
                .orderByDesc(Message::getCreateTime);
        
        if (type != null) {
            wrapper.eq(Message::getType, type);
        }
        if (status != null) {
            wrapper.eq(Message::getStatus, status);
        }
        
        return selectPage(page, wrapper);
    }

    /**
     * 批量标记消息为已读
     */
    default int batchMarkAsRead(@Param("messageIds") List<Long> messageIds, @Param("receiverId") Long receiverId) {
        return update(null, new LambdaUpdateWrapper<Message>()
                .in(Message::getId, messageIds)
                .eq(Message::getReceiverId, receiverId)
                .set(Message::getStatus, 1)
                .set(Message::getReadTime, LocalDateTime.now()));
    }

    /**
     * 查询最新消息（用于实时推送）
     */
    default List<Message> selectLatestMessages(Long receiverId, Integer limit) {
        return selectList(new LambdaQueryWrapper<Message>()
                .eq(Message::getReceiverId, receiverId)
                .eq(Message::getStatus, 0)
                .eq(Message::getDeleted, 0)
                .orderByDesc(Message::getCreateTime)
                .last("LIMIT " + limit));
    }
} 